<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='确认单号'>
              <a-input placeholder='请输入确认单号' v-model='queryParams.no'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='财务确认人'>
              <a-input placeholder='请输入财务确认人' v-model='queryParams.finaSureUser'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='5' :lg='7' :md='8' :sm='24'>
            <a-form-item label='财务是否确认'>
              <a-select v-model='queryParams.isSure' placeholder='请选择状态'>
                <a-select-option v-for='(d,i) in stateList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="7" :lg="7" :md="8" :sm="24">
              <a-form-item label="财务确认日期">
                <a-range-picker :style="{width: '100%'}"  format="YYYY-MM-DD"
                                :placeholder="['开始时间', '结束时间']"
                                v-model='rangePikerDate'
                                @change="onQueryDateChange" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='search' icon='search'>查询</a-button>
              <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
      <!--      <a-button @click='addModalShow' type='primary' icon='plus'>新增</a-button>-->
      <a-button type='primary' icon='download' @click="handleExportXls('财务确认单主表')">导出Excel</a-button>

<!--      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='flowerPreBatchDelete(selectedRowKeys)'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='flowerPreDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :scroll='{ x: true }'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='mainPaginationChange'>

        <!--        （0正常，1删除，2撤销）-->

        <span slot='state' slot-scope='text, record'>
          <span v-if='text==null || text=="" || text==0'>正常</span>
          <span v-if='text!=null && text!="" && text==1' class='ant-tag-red' style='color:red;'>删除</span>
          <span v-if='text!=null && text!="" && text==2' class='ant-tag-red' style='color:red;'>撤销</span>
        </span>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>

        <span slot='action' slot-scope='text, record'>
          <a v-if=' !record.finaSureUser || record.finaSureUser==null || record.finaSureUser=="" ' @click='editModalShow(record)'>财务确认</a>
          <a v-else @click='editModalShow(record)'>查看</a>
          <a-divider v-if='record.finaSureUser'  type='vertical' />
          <a v-if='record.finaSureUser'  @click='handleExportXlsAccont(record)'
             style='margin-right: 5px;color: red !important;'>结算单</a>
<!--          <a-divider v-if='record.finaSureUser!=""'  type='vertical' />-->

<!--          <a-dropdown>-->
<!--            <a class='ant-dropdown-link'>更多 <a-icon type='down' /></a>-->
<!--            <a-menu slot='overlay'>-->
<!--              <a-menu-item>-->
<!--                <a-popconfirm title='确定删除吗?' @confirm='() => flowerPreDelete(record.id)'>-->
<!--                  <a>删除</a>-->
<!--                </a-popconfirm>-->
<!--              </a-menu-item>-->
<!--            </a-menu>-->
<!--          </a-dropdown>-->
        </span>

      </a-table>
    </div>

    <!--    <flowerPre-modal ref="modalForm" @ok="modalFormOk"></flowerPre-modal>-->
    <a-modal v-model:visible='addOrEditVisible' width='75%' :title='firstModalTitle' @ok='flowerPreAddOrEdit'
             :maskClosable='false'>
      <div>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block'>确认单号：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input-number disabled v-model='flowerPre.no' placeholder='自动生成' style='width: 100%' />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>出库日期：</div>
            <div style='display: inline-block;width: 70%'>
              <a-date-picker :disabled='flowerPre.finaSureUser!=="" && flowerPre.finaSureUser!=null'
                             v-model:value='flowerPre.stockOutTime'
                             :disabled-date="disabledDate"
                             placeholder='请选择出库日期' disabled/>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>账期：</div>
            <div style='display: inline-block;'>
              <a-radio-group v-model='flowerPre.period' @change='periodChange' disabled>
                <a-radio v-for='(item,index) in periodList' :value='item'>{{ item}}</a-radio>
              </a-radio-group>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>渠道：</div>
            <div style='display: inline-block;'>
              <a-select v-model='flowerPre.channel' placeholder='请选择渠道' style='width: 130px;' @change='channelChange' disabled>
                <a-select-option v-for='(d,i) in channelList' :key='d.id' :value='d.channel'>{{d.channel}}
                </a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span='8' v-show="accountnoShow">
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block'>账号：</div>
            <div style='display: inline-block;'>
              <a-select v-model='flowerPre.accountno' placeholder='请选择账号' style='width: 130px;' disabled>
                <a-select-option v-for='(d,i) in accountnoList' :key='d.id' :value='d.account'>{{d.account}}
                </a-select-option>
              </a-select>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>是否开票：</div>
            <div style='display: inline-block;width: 70%'>
              <a-radio-group :disabled='flowerPre.finaSureUser!="" && flowerPre.finaSureUser!=null '
                             v-model='flowerPre.isinvoice' @change='isinvoiceChange' disabled>
                <a-radio value='是'>是</a-radio>
                <a-radio value='否'>否</a-radio>
              </a-radio-group>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>客户：</div>
            <div style='display: inline-block;width: 80%'>
              <a-input :disabled='flowerPre.finaSureUser!="" && flowerPre.finaSureUser!=null ' v-model='flowerPre.user'
                       placeholder='请输入客户名称' disabled/>
            </div>
          </a-col>
          <a-col :span='12'>
            <div style='display: inline-block;color: red;'>*</div>
            <div style='display: inline-block;'>地址：</div>
            <div style='display: inline-block;width: 88%'>
              <a-input :disabled='flowerPre.finaSureUser!="" && flowerPre.finaSureUser!=null '
                       v-model='flowerPre.address' placeholder='请输入地址' disabled/>
            </div>
          </a-col>
        </a-row>

        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block'>销售确认人：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input disabled v-model='flowerPre.sealSureUser' placeholder='销售确认人为登陆用户' disabled/>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block'>销售确认日期：</div>
            <div style='display: inline-block;width: 60%'>
              <a-date-picker v-model:value='flowerPre.sealSureTime' :valueFormat='dateFormat'
                             :disabled-date="disabledDate"
                             placeholder='确认日期为当前日期' disabled/>
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block'>数量：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input-number disabled v-model='flowerPre.number' placeholder='保存后自动计算' style='width: 100%' disabled/>
            </div>
          </a-col>
        </a-row>
        <a-row style='margin-top: 10px'>
          <a-col :span='8'>
            <div style='display: inline-block'>总价：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input-number disabled v-model='flowerPre.toalprice' placeholder='保存后自动计算' style='width: 100%' />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block'>财务确认日期：</div>
            <div style='display: inline-block;width: 60%'>
              <a-date-picker v-model:value='flowerPre.finaSureTime' :valueFormat='dateFormat' disabled />
            </div>
          </a-col>
          <a-col :span='8'>
            <div style='display: inline-block'>财务确认人：</div>
            <div style='display: inline-block;width: 60%'>
              <a-input v-model='flowerPre.finaSureUser'placeholder='确认人为登陆用户' disabled />
            </div>
          </a-col>
        </a-row>
      </div>
      <a-divider />
      <div style='margin-top: -20px'>
        <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px'>销售商品</div>
        <!--        <a-button type='primary' icon='plus' @click='varietyModalShow'>新增</a-button>-->
        <div style='display: inline-block;margin-left: 400px;font-size: 18px'>
          <span>总价合计：</span><span style='color: red'>{{ allTotalPrice }}</span>
        </div>
        <div style='margin-top: 7px'>
          <a-table :columns='varietyColumns' :data-source='varietyDataSource'
                   bordered row-key='uuid'
                   :loading='varietyLoading'
                   :scroll="{ x: true, y: 300 }">
            <!--            <template v-for="colNumber in ['number']" :slot='colNumber' slot-scope='text, record, index'>-->
            <!--              <div :key='colNumber' style='float: left;margin-right: 0'>-->
            <!--                <input disabled v-model:value='record.number' placeholder='请输入数量' />-->
            <!--              </div>-->
            <!--            </template>-->
            <template v-for="colSnumber in ['snumber']" :slot='colSnumber' slot-scope='text, record, index'>
              <div :key='colSnumber' style='float: left;margin-right: 0'>
                <a-input disabled v-model:value='record.snumber' placeholder='请输入销售数量' />
              </div>
            </template>
            <template v-for="colPrice in ['price']" :slot='colPrice' slot-scope='text, record, index'>
              <div :key='colPrice' style='float: left;margin-right: 0'>
                <a-input disabled v-model:value='record.price' placeholder='请输入销售单价' />
              </div>
            </template>
            <!--            <template slot='operation' slot-scope='text, record'>-->
            <!--              <a-popconfirm v-if='varietyDataSource.length' title='确定删除?'-->
            <!--                            @confirm='() => varietyDelete(record.superId)'>-->
            <!--                <a>删除</a>-->
            <!--              </a-popconfirm>-->
            <!--            </template>-->
          </a-table>
        </div>
      </div>
      <template slot='footer'>
        <a-button @click='cancelOutOrderAddOrEdit()'>取消</a-button>
        <a-button v-if='flowerPre.finaSureUser' type='danger' @click='backOutByFinal'>撤销确认</a-button>
        <a-button v-if='!flowerPre.finaSureUser' type='primary' @click='flowerPreAddOrEdit'>财务确认</a-button>
      </template>
    </a-modal>

  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerPreModal from './modules/FlowerPreModal'
import { downFile } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import { ifInteger, ifNumber } from '../../utils/ifNumber'
import {
  getFlowerVarietys, getFlowerPre, getFlowerPreinfoByMainId, flowerPreAdd, flowerPreEdit,
  flowerPreDelete, flowerPreDeleteBatch, backOut, finSureOut, getFlowerChannel, getFlowerAccountByMainId,
  period, queryFlowerBase, queryGreenhouseByPd
} from '../../api/api'
import { getUuid } from '../../utils/uuid'
import moment from 'moment'

export default {
  name: 'FlowerFinanceList',
  mixins: [JeecgListMixin],
  components: {
    FlowerPreModal
  },
  data() {
    return {
      queryParams: {// 主页查询
        no: '',//确认单号
        finaSureUser: '',//财务确认人
        isSure: '',//是否财务确认
        sfDate:'',//开始时间
        efDate:'',//结束时间
      },
      rangePikerDate:[],
      queryVarietyParams: {// 商品选择弹窗的查询
        variety: '',
        varietyCode: ''
      },
      //选择财务是否确认的list
      stateList: [{ id: '', value: '全部' }, { id: 1, value: '是' }, { id: 2, value: '否' }],
      description: '财务确认单主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '确认单号',
          align: 'center',
          dataIndex: 'no',
          width: 140
        },{
          title:'账期',
          align:"center",
          width:100,
          dataIndex: 'period'
        },
        /*{
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          width: 100,
        },*/
        // {
        //   title: '数量',
        //   align: 'center',
        //   dataIndex: 'number'
        // },
        {
          title: '总价',
          align: 'center',
          dataIndex: 'toalprice',
          width: 140
        },
        {
          title: '出库日期',
          align: 'center',
          dataIndex: 'stockOutTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 100
        },{
          title: '销售确认日期',
          align: 'center',
          dataIndex: 'sealSureTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 100
        },
        {
          title: '销售确认人',
          align: 'center',
          dataIndex: 'sealSureUser',
          width: 100
        },
        {
          title: '财务确认日期',
          align: 'center',
          dataIndex: 'finaSureTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 100
        },
        {
          title: '财务确认人',
          align: 'center',
          dataIndex: 'finaSureUser',
          width: 100
        },/*{
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' },
          width: 100
        },*/
        {
          title: '渠道',
          align: 'center',
          dataIndex: 'channel',
          ellipsis: true,
          width: 80
        },
        {
          title: '账号',
          align: 'center',
          dataIndex: 'accountno',
          ellipsis: true,
          width: 100
        },
        {
          title: '是否开票',
          align: 'center',
          dataIndex: 'isinvoice',
          width: 90
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 100
        },

        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUser_dictText',
          width: 100
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flower/flowerPre/list',
        delete: '/flower/flowerPre/delete',
        deleteBatch: '/flower/flowerPre/deleteBatch',
        exportXlsUrl: '/flower/flowerPre/exportXls',
        importExcelUrl: 'flower/flowerPre/importExcel'
      },
      dictOptions: {},
      flowerPreDataSource: [],
      // sourceBaseList: [],//基地列表
      // sourceGreenhouseList: [],//地块列表
      firstModalTitle: '',
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      varietyLoading: true,
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      varietyVisible: false,//是否打开商品选择的弹窗
      flowerPre: {
        sourceBase: '',//基地
        sourceGreenhouse: '',//地块
        no:'',//确认单号
        period:'',//账期
        isinvoice:'',//是否开票
        number: '',//数量
        toalprice: '',//总价
        sealSureTime: '',//销售确认日期
        sealSureUser: '',//销售确认人
        finaSureTime: '',//财务确认日期
        finaSureUser: '',//财务确认人
        channel: '',//渠道
        accountno:'',//账号
      },
      channelList: [],
      accountnoList: [],
      accountnoShow: false,//第一个弹窗中是否显示账号的选择框
      dateFormat: 'YYYY-MM-DD',
      varietyColumns: [// 第一个弹窗的表头
        {
          title:'基地',
          align:"center",
          dataIndex: 'sourceBase_dictText',
          width: 120,
        },{
          title:'大棚',
          align:"center",
          dataIndex: 'sourceGreenhouse_dictText',
          width: 100,
        },{
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          width: 100
        }, {
          title: '产品',
          dataIndex: 'variety',
          width: 100
        }, {
          title: '商品编码',
          dataIndex: 'varietyCode',
          width: 100
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications',
          width: 100
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength',
          width: 100
        }, /*{
          title: '等级',
          dataIndex: 'classes',
          width: 100
        },*/
        // {
        //   title: '数量',
        //   dataIndex: 'number',
        //   scopedSlots: { customRender: 'number' }
        // },
        {
          title: '销售数量',
          dataIndex: 'snumber',
          scopedSlots: { customRender: 'snumber' },
          width: 100
        }, {
          title: '单价',
          dataIndex: 'price',
          scopedSlots: { customRender: 'price' },
          width: 100
        }, {
          title: '总价',
          dataIndex: 'totalprice',
          width: 100
        },
        /*{
          title: '操作',
          dataIndex: 'operation',
          width: 100,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }*/
      ],
      varietyDataSource: [],// 第一个弹窗中的商品列表
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      allTotalPrice: 0,//编辑弹窗中所有商品的总价
      periodList:[],//从后台取回的账期列表（上个账期，当前账期，下个账期）
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.getChannel()
    this.getPeriod()
  },
  mounted() {
    this.queryFlowerPre()
    this.queryFlowerBase()
  },
  methods: {
    search() {// 主页中根据条件查询
      this.mainPagination.current=1
      this.queryFlowerPre()
    },
    onQueryDateChange(date, dateString){// 日期段选择改变时的回调
      this.queryParams.sfDate = dateString[0]
      this.queryParams.efDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页查询
        no: '',//确认单号
        finaSureUser: '',//财务确认人
        isSure: '',//是否财务确认
        sfDate:'',//开始时间
        efDate:'',//结束时间
      }
      this.rangePikerDate=[]
      this.search()
    },
    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryFlowerPre()
    },
    queryFlowerPre() {// 获取销售单
      this.loading=true
      this.flowerPreDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params={...this.queryParams,...params}
      getFlowerPre(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.flowerPreDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading=false
      })
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      this.flowerPre = {
        no:'',//确认单号
        period:this.periodList.length===1?this.periodList[0]:this.periodList[1],//账期
        isinvoice:'',//是否开票
        number: '',//数量
        toalprice: '',//总价
        sealSureTime: '',//销售确认日期
        sealSureUser: '',//销售确认人
        finaSureTime: '',//财务确认日期
        finaSureUser: '',//财务确认人
        channel: '',//渠道
        accountno:'',//账号
      }
      this.varietyDataSource = []
      this.allTotalPrice = 0
      this.getPeriod()
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '查看'
      this.flowerPre = record
      if (this.flowerPre.accountno!==''){//打开编辑界面时如果账号有数据的话，要把账号显示出来
        this.accountnoShow=true
      }
      this.varietyDataSource.length = 0
      this.allTotalPrice = 0
      this.queryFlowerPreinfo(record.id)
      this.setPeriod()
      this.addOrEditVisible = !this.addOrEditVisible
    },
    varietyModalShow() {//打开第二个弹窗
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择商品而实际上没有选择任何商品的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.selectVariety = {}
      this.varietyPagination = {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 5,//每页中显示5条数据
        showSizeChanger: true,
        pageSizeOptions: ['5', '10', '15', '20'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryFlowerVarietys()
      this.varietyVisible = !this.varietyVisible
    },
    queryFlowerPreinfo(id) {//获取第一个弹窗的商品数据
      this.varietyLoading=true
      let params = {// 因为第一个弹窗中的表格会有新增商品的数据，因此无法使用分页，故将pageSize设大一些
        pageNo: 1,
        pageSize: 1000,
        id: id
      }
      getFlowerPreinfoByMainId(params).then(res => {
        if (res.success) {
          let records = res.result.records
          for (let item of records) {
            this.allTotalPrice = 0
            for (let item of records) {
              if(!item.totalprice){
                item.totalprice = 0
              }
              this.allTotalPrice += item.totalprice*10/10  // 计算总价合计
            }
            this.allTotalPrice = this.allTotalPrice.toFixed(2)
          }
          this.varietyDataSource = records
          this.varietyDataSource.map(item => {// 将uuid封装进varietyDataSource中的各用户对象中,为table中的key使用
            item.uuid = getUuid()
          })
        } else {
          this.$message.error(res.message)
        }
        this.varietyLoading=false
      })
    },
    varietyDelete(superId) {// 第一个弹窗中删除商品
      const dataSource = [...this.varietyDataSource]
      this.varietyDataSource = dataSource.filter(item => item.superId !== superId)
    },
    flowerPreAddOrEdit() {// 确定新增或编辑销售单

      let allNumberFlag = true//是否所有的商品都有数量的标识

      if (this.flowerPre.number === '') {
        this.$message.error('请输入数量')
      } else if (this.flowerPre.toalprice === '') {
        this.$message.error('请输入总价')
      } else {
        for (let item of this.varietyDataSource) {
          // if (item.number === '' || item.number === null) {
          //   this.$message.error('请输入数量')
          //   allNumberFlag = false
          //   return
          // }
          if (item.snumber === '' || item.snumber === null) {
            this.$message.error('请输入销售数量')
            allNumberFlag = false
            return
          }
          if (item.price === '' || item.price === null) {
            this.$message.error('请输入单价')
            allNumberFlag = false
            return
          }
          // if (!ifInteger(item.number)){
          //   this.$message.error('商品数量必须为正整数');
          //   return
          // }
          if (!ifInteger(item.snumber)) {
            this.$message.error('销售数量必须为正整数')
            return
          }
          if (!ifNumber(item.price)) {
            this.$message.error('单价必须为数字')
            return
          }

        }
        if (allNumberFlag) {
          // 将varietyDataSource中每个对象里面的id字段删除,此id字段是为了table中的key而在前端生成的
          /*for (let item of this.varietyDataSource) {
            delete item.id
          }*/
          this.flowerPre.flowerPreinfoList = this.varietyDataSource// 将商品列表封装近flowerPre中
          // if (this.addOrEditFlag === 'add') {// 新增销售单的情况
          //   flowerPreAdd(this.flowerPre).then(res => {
          //     if (res.success) {
          //       this.queryFlowerPre()
          //       this.$message.success('新增销售成功')
          //     } else {
          //       this.$message.error(res.message)
          //     }
          //   })
          // } else {
          //   flowerPreEdit(this.flowerPre).then(res => {// 编辑销售单的情况
          //     if (res.success) {
          //       this.queryFlowerPre()
          //       this.$message.success('编辑销售成功')
          //     } else {
          //       this.$message.error(res.message)
          //     }
          //   })
          // }

          finSureOut({ id: this.flowerPre.id }).then(res => {// 编辑销售单的情况
            if (res.success) {
              // this.queryFlowerPre()
              this.$message.success('确认成功')
              this.queryFlowerPre()
            } else {
              this.$message.error(res.message)
            }
          })
        }
        this.selectedRowKeys.length = 0//使新增或编辑后不显示批量删除的按钮
        this.addOrEditVisible = !this.addOrEditVisible
      }
    },
    backOutByFinal(id) {
      backOut({ id: this.flowerPre.id }).then(res => {// 编辑销售单的情况
        if (res.success) {
          this.$message.success('撤销成功')
          this.queryFlowerPre()
        } else {
          this.$message.error(res.message)
        }
      })
      this.addOrEditVisible = !this.addOrEditVisible
    },
    flowerPreDelete(id) {
      flowerPreDelete({ id: id }).then(res => {
        if (res.success) {
          this.queryFlowerPre()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    cancelOutOrderAddOrEdit() {
      this.addOrEditVisible = false
    },
    flowerPreBatchDelete(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerPreDeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryFlowerPre()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    handleExportXlsAccont(record) {
      getFlowerPreinfoByMainId({ "id":record.id }).then(res => {
        if (res.success) {
          let records = res.result.records
          let name = ''
          if(records.length>0){
            name = records[0].cost_dictText
          }
          let fileName = name  + '结算单' + record.no
          let param = this.getQueryParams()
          if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
            param['selections'] = this.selectedRowKeys.join(',')
          }
          // console.log('导出参数', param)
          let urlss = '/flower/flowerPre/exportXlsForAccont'
          downFile(urlss, record).then((data) => {
            if (!data) {
              this.$message.warning('文件下载失败')
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
            } else {
              let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName + '.xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
            }
          })

        } else {
          this.$message.error(res.message)
        }
      })
    },
    //是否开票的单项
    isinvoiceChange(e) {
      this.flowerPre.isinvoice = e.target.value
    },
    //获取渠道
    getChannel() {
      getFlowerChannel().then(res => {
        if (res.success) {
          this.channelList = res.result.records
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //渠道选择框的change
    channelChange(value, option) {
      this.accountnoList.length=0
      this.flowerPre.accountno=''
      this.varietyDataSource.length=0//处理重新选择渠道后，要置空之前已选择的商品
      this.getAccountnoByMainId(option.key)
    },
    //根据渠道id获取账号
    getAccountnoByMainId(channelId) {
      let params={id:channelId}
      getFlowerAccountByMainId(params).then(res => {
        if (res.success) {
          this.accountnoList = res.result
          if (this.accountnoList.length===0){
            this.accountnoShow=false
          }else {
            this.accountnoShow=true
          }
        } else {
          this.$message.error('未找到对应的账号')
        }
      })
    },
    // 日期选择框中不可选择的日期
    disabledDate(current) {
      return current < moment().subtract(1, "day") ;//当前日期以前不可用
    },
    getPeriod(){
      period().then(res=>{
        this.periodList=res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.flowerPre.period = e.target.value
    },
    //设置账期（打开编辑弹窗时用）
    setPeriod(){
      period().then(res=>{
        this.periodList=res
        if (this.periodList.length===1){//账期开关关闭时
          this.periodList.push(this.flowerPre.period)
          this.periodList=Array.from(new Set(this.periodList))//去重
          this.periodList.sort()//升序排序
        }
      })
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>